package com.itdong.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Component
public class StringRedisUtils {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public static StringRedisUtils INTANCE = new StringRedisUtils();

    @PostConstruct
    public void init(){
        INTANCE.stringRedisTemplate = stringRedisTemplate;
    }

    public static void setString(String key, String value){
        try {
            System.out.println("准备进redis之前的数据："+key+"-"+value);
            INTANCE.stringRedisTemplate.opsForValue().set(key,value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static <T> void setObject(String key, T value){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            String s = objectMapper.writeValueAsString(value);
            System.out.println("准备进redis之前的数据："+key+"-"+s);
            INTANCE.stringRedisTemplate.opsForValue().set(key,s);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public static <T> T get(String key, Class<T> res){
        try {
            String s = INTANCE.stringRedisTemplate.opsForValue().get(key);
            System.out.println("redis中的数据："+key+"-"+s);
            ObjectMapper objectMapper = new ObjectMapper();
            T t = objectMapper.readValue(s, res);
            return t;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
